//
//  ADCollectionView.swift
//  手账
//
//  Created by zhuxiaoxiang on 2018/11/16.
//  Copyright © 2018年 zhuxiaoxiang. All rights reserved.
//

import UIKit

class ADCollectionView: UICollectionView {
    
    weak var adDelegate: ADCollectionViewProtocol?
    
    var currentIndex = 1
    
    var timer: Timer!
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension ADCollectionView {
    // 配置
    func set() {
        self.delegate = self
        self.dataSource = self
        self.backgroundColor = UIColor.white
        self.isUserInteractionEnabled = false
        self.register(ADCollectionViewCell.self, forCellWithReuseIdentifier: self.adDelegate?.reuseIdentifier ?? "ADCell")
        self.startTimer()
    }
    // 启动timer
    func startTimer() {
        self.timer = Timer(timeInterval: self.adDelegate?.interval ?? 3, target: self, selector: #selector(autoNext), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer, forMode: .commonModes)
        if let delegate = self.adDelegate {
            if delegate.dataArray.count > 1 {
                self.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false)
            }
        }
    }
}

// MARK: - 代理
extension ADCollectionView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let delegate = self.adDelegate {
            return delegate.dataArray.count + 2
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.adDelegate?.reuseIdentifier ?? "ADCell", for: indexPath) as! ADCollectionViewCell
        if let delegate = self.adDelegate {
            let arr = delegate.dataArray
            var obj = NSObject()
            if indexPath.item == 0 {
                obj = arr[arr.count - 1]
            }else if indexPath.item == arr.count + 1 {
                obj = arr[0]
            }else {
                obj = arr[indexPath.item - 1]
            }
            if obj.isKind(of: UIImage.self) {
                cell.adImageView.image = obj as? UIImage
            }
            if obj is String {
                let url = URL(string: (obj as? String)!)
                do {
                    let data = try Data.init(contentsOf: url!, options: Data.ReadingOptions.alwaysMapped)
                    cell.adImageView.image = UIImage.init(data: data)
                }catch  {
                    print(error)
                }
            }
        }
        return cell
    }
}

extension ADCollectionView : UIScrollViewDelegate {
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        timer.fireDate = Date.distantPast
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        currentIndex = Int(self.contentOffset.x / (ADConfig.Width - 100))
        print(currentIndex)
    }
    
    
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        timer.fireDate = Date.distantFuture
    }
}

extension ADCollectionView {
    @objc func autoNext() {
        currentIndex += 1
        if let delegate = self.adDelegate {
            if currentIndex == delegate.dataArray.count + 1 {
                currentIndex = 1
                self.scrollToItem(at: IndexPath(item: 0, section: 0), at: UICollectionViewScrollPosition.centeredHorizontally, animated: false)
                self.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionViewScrollPosition.centeredHorizontally, animated: true)
            }else {
                if currentIndex <= delegate.dataArray.count {
                     self.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionViewScrollPosition.centeredHorizontally, animated: true)
                }else {
                    currentIndex = 0
                }
            }
            }
        }
}
